package org.example.work2.tcc.order.service.impl;


import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.example.work2.tcc.order.dto.Order;
import org.example.work2.tcc.order.mapper.OrderMapper;
import org.example.work2.tcc.order.service.OrderAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class OrderActionImpl implements OrderAction {
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public boolean createOrderPrepare(BusinessActionContext actionContext, Long id, String accountCode, String productId, Integer productCounts, Integer totalPrice) throws Exception {

        log.info("[createOrderPrepare] 当前 XID: {}", actionContext.getXid());
        Order order = new Order();
        order.setId(id);
        order.setProductCounts(productCounts);
        order.setAccountCode(accountCode);
        order.setTotalPrice(totalPrice);
        order.setProductId(productId);
        // 保存订单
        log.info("[createOrderPrepare] 开始创建订单: {}", order);
        int saveOrder = orderMapper.saveOrder(order);
        if(saveOrder <= 0){
            log.warn("[createOrderPrepare] 创建订单 {} 失败", order);
            throw new Exception("创建订单失败");
        }
        log.info("[createOrderPrepare] 创建订单成功: {}", order);
        return true;
    }

    @Override
    @Transactional
    public boolean createOrderCommit(BusinessActionContext actionContext) throws Exception {

        log.info("[createOrderCommit] 当前 XID: {}", actionContext.getXid());

        Long orderId = (Long)actionContext.getActionContext("id");
        int commitOrder = orderMapper.saveOrderCommit(orderId);
        if(commitOrder <= 0){
            throw new Exception("[createOrderCommit] 失败");
        }
        log.info("[createOrderCommit] 成功");
        return true;
    }

    @Override
    @Transactional
    public boolean createOrderRollBack(BusinessActionContext actionContext) throws Exception {
        log.info("[createOrderRollBack] 当前 XID: {}", actionContext.getXid());

        Long orderId = (Long)actionContext.getActionContext("id");
        int flag = orderMapper.saveOrderRollBack(orderId);
        if(flag <= 0){
            throw new Exception("[createOrderRollBack] 失败");
        }
        log.info("[createOrderRollBack] 成功");
        return true;
    }
}
